﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using Facebook;
using System.Collections.ObjectModel;
using System.Dynamic;
using WpfApplication1.ViewModel;
using WpfApplication1.Utils;
using WpfApplication1.Controls;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        // Khu vực Binding Data
        private RootData rootdata = new RootData();
        private const string AppId = "268194079914408";
        private const string ExtendedPermissions =
            "user_about_me,publish_stream,offline_access,read_stream,friends_about_me,friends_birthday,friends_education_history,friends_location,manage_notifications,read_requests,user_photos,user_notes,user_work_history,user_religion_politics,user_relationships,user_religion_politics,user_education_history,user_birthday,user_likes,email";
        public static string AccessToken;
        private CFacebookServer fbServer;
        private AutoUpdate autoupdate = new AutoUpdate();
        private AnnouncementSystem announcementSys = new AnnouncementSystem();

        private InternetConnection Connection;
        private bool IsConnected;
        private WindowDetail home_detail;
        private WindowDetail wall_item_detail;
        private WindowsDetail profile_detail;
        private WindowsDetail album_detail;
        private System.Threading.Thread thread;
        private System.Threading.Thread thread2;
        private System.Threading.Thread thread_load_friend_more;
        private System.Threading.Thread thread_load_profile_more;
        private System.Threading.Thread thread_load_more_note;
        private System.Threading.Thread thread_search_friend = null;

        private MyNotifyIcon notifyIcon;
        private Storyboard MainWindowFadeInStoryBoard;
        private Storyboard MainWindowFadeOutStoryBoard;
        public static string load_stt = "home";


        private List<object> mylist = new List<object>();


        public MainWindow()
        {
        Begin:
            // Insert code required on object creation below this point.
            Connection = new InternetConnection();
            IsConnected = Connection.IsConnect;
            if (IsConnected == false)
            {
                try
                {
                    MessageBoxResult result = MessageBox.Show("NO Internet Connection \n Do you want to restart app and check your Internet Connection \n make sure your computer connect to internet", "Error", MessageBoxButton.YesNo, MessageBoxImage.Information);
                    if (result == MessageBoxResult.Yes)
                    {
                        goto Begin;
                    }
                    if (result == MessageBoxResult.No)
                    {
                        Application.Current.Shutdown();
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("Have some errors, sorry");
                }
            }
            DataContext = rootdata;
            
            if (!DoLogin())
            {
                return;
            }
            LoadPersonalInfo();
            this.InitializeComponent();
            gotoRightBottom();
            MainWindowFadeInStoryBoard = (Storyboard)FindResource("MainWindowFadeInStoryBoard");
            MainWindowFadeInStoryBoard.Completed += new EventHandler(FadeInCompleted);
            MainWindowFadeOutStoryBoard = (Storyboard)FindResource("MainWindowFadeOutStoryBoard");
            MainWindowFadeOutStoryBoard.Completed += new EventHandler(FadeOutCompleted);
            InitNotifyIcon();
            FillPersonalInfo();
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(LoadHomeFeed));
            thread.Start();
            System.Threading.Thread threadnotice = new System.Threading.Thread(new System.Threading.ThreadStart(LoadNotification));
            threadnotice.Start();
            System.Threading.Thread thread1 = new System.Threading.Thread(new System.Threading.ThreadStart(LoadFriendRequest));
            thread1.Start();
            Connect_Status.DataContext = Connection;
            //ShowConnectionStatus();
            PrepairAutoUpdate();
            autoupdate.StartAutoUpdateHomeFeed();
            autoupdate.StartAutoupdateNotification();
            autoupdate.StartAutoupdateFriendRequest();
            autoupdate.StartAutoUpdateWall();

        }

        /*
         * Khởi tạo IconNotify
         */

        private void InitNotifyIcon()
        {
            notifyIcon = new MyNotifyIcon();
            notifyIcon.MouseDoubleClick += new MyNotifyIcon.MouseLeaveHandler(ShowMainWindow);

            System.Windows.Forms.ContextMenu menu_taskbar = new System.Windows.Forms.ContextMenu();
            System.Windows.Forms.MenuItem menu_exit = new System.Windows.Forms.MenuItem("Exit");

            menu_exit.Click += new EventHandler(menu_exit_Click);
            menu_taskbar.MenuItems.Add(menu_exit);
            notifyIcon.myNotifyIcon.ContextMenu = menu_taskbar;
        }

        #region Ẩn và Hiện Main Windows
        /*
         * Hàm hiện Main Windows
         */
        private void ShowMainWindow()
        {
            MainWindowFadeOutStoryBoard.Stop();
            this.Opacity = 1;
            if (MainBorder.Opacity == 0)
                MainWindowFadeInStoryBoard.Begin();
        }

        /*
         * Hàm ẩn Main Windows
         */
        private void HideMainWindow(object sender, RoutedEventArgs e)
        {
            MainWindowFadeInStoryBoard.Stop();
            if ((MainBorder.Opacity == 1) && (this.Opacity == 1))
                MainWindowFadeOutStoryBoard.Begin();
            else
            {
                MainBorder.Opacity = 0;
                this.Opacity = 0;
            }
        }

        void FadeInCompleted(object sender, EventArgs e)
        {
            this.Opacity = 1;
        }

        void FadeOutCompleted(object sender, EventArgs e)
        {
            this.Opacity = 0;
        }
        #endregion

        private void menu_exit_Click(object sender, System.EventArgs e)
        {
            // TODO: Add event handler implementation here.
            Application.Current.Shutdown();

        }
        private void CheckConnection()
        {

            try
            {
                Connection = new InternetConnection();
                IsConnected = Connection.IsConnect;
                Connect_Status.DataContext = Connection;
            }
            catch
            {
                return;
            }
        }

        private void gotoRightBottom()
        {
            Left = SystemParameters.WorkArea.Width - Width;
            Top = SystemParameters.WorkArea.Height - Height;
        }

        private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            popup_menu.IsOpen = true;
        }

        /*
         * Hiện và xác nhận đăng nhập
         */
        private bool DoLogin()
        {
            try
            {
                LoginForm myLogin = new LoginForm(AppId, ExtendedPermissions);
                myLogin.ShowDialog();

                if (myLogin.AccessToken == null)
                {
                    MessageBox.Show("Exit :(");
                    Application.Current.Shutdown();
                    return false;
                }
                else
                {
                    AccessToken = myLogin.AccessToken;
                    fbServer = new CFacebookServer(AccessToken);
                    return true;
                }
            }
            catch
            {
                return false;
            }

        }

        /*
         * Load thông tin chung của người dùng, avatar, name,...
         */
        private void LoadPersonalInfo()
        {
            if (AccessToken == null)
            {
                MessageBox.Show("AccessToken Error!");
                this.Close();
            }
            try
            {
                FacebookClient fb = new FacebookClient(AccessToken);

                IDictionary<string, object> result = (IDictionary<string, object>)fb.Get("me");
                if (result == null)
                {
                    MessageBox.Show("Error at LoadPersonalInfo");
                    this.Close();
                }
                rootdata.personalInfo = result;
            }
            catch
            {
                MessageBox.Show("Khong the ket noi toi facebook");

            }
        }

        /*
         * Điền các thông tin người dùng ra giao diện.
         * Sẽ chuyển đổi thành Binding cho phần này
         */
        private void FillPersonalInfo()
        {
            try
            {
                if (rootdata.personalInfo == null)
                {
                    MessageBox.Show("Error at FillPersonalInfo");
                    this.Close();
                }
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                string urlPic = string.Format("https://graph.facebook.com/{0}/picture?type={1}", (string)rootdata.personalInfo["id"], "square");
                bitmap.UriSource = new Uri(urlPic);
                bitmap.EndInit();
                profilepic.Source = bitmap;

                profilename.Text = (string)rootdata.personalInfo["name"];
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        /*
         * Load các notification từ facebook
         */
        private void LoadNotification()
        {
            try
            {
                ObservableCollection<NotificationViewModel> ds = new ObservableCollection<NotificationViewModel>();
                ds = fbServer.GetListNotifications();
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                {
                    rootdata.AddNotify(ds);
                }));
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        /*
         * Load các Friend Request từ facebook
         */
        private void LoadFriendRequest()
        {
            try
            {
                ObservableCollection<FriendRequestViewModel> ds = new ObservableCollection<FriendRequestViewModel>();
                ds = fbServer.GetListFriendRequest();
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                    new System.Action(delegate()
                    {
                        rootdata.AddFriendRequest(ds);
                    }));
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        /*
         * Load Home Feeds từ facebook và lưu vào Root Data
         */
        void LoadHomeFeed()
        {
            try
            {
                IDictionary<string, object> resource_home = fbServer.GetHomeFeed();
                //autoupdate.UpdateTimeHomeFeed();
                ObservableCollection<HomeFeedViewModel> temp = fbServer.ConvertToListFeeds(resource_home);
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                    new System.Action(delegate()
                    {
                        rootdata.AddHomeFeeds(temp);
                        loadingcontrol_home.Visibility = Visibility.Collapsed;
                    }));
            }
            catch
            {
                return;
            }

        }

        /*
         * Bắt sự kiện thay đổi Scroll của Home Feeds
         */
        private void DoChanged(object sender, System.Windows.Controls.ScrollChangedEventArgs e)
        {
            try
            {
                CheckConnection();
                if (e.ExtentHeight == (e.VerticalOffset + e.ViewportHeight) && ((LoadingIcon.Text == "Loading") || (IsConnected == true)))
                {
                    if (thread != null) // Nếu tồn tại thread đang running thì sẽ ko create thread nào nữa
                        if (thread.IsAlive)
                            return;
                    loadingcontrol_home.Visibility = Visibility.Visible;
                    thread = new System.Threading.Thread(new System.Threading.ThreadStart(LoadHomeFeedMore));
                    thread.Start();
                }
            }
            catch
            {
                return;
            }
            // TODO: Add event handler implementation here.


        }

        /*
         * Load thêm Feeds của phần HomeFeeds
         */
        private void LoadHomeFeedMore()
        {
            try
            {
                CheckConnection();
                IDictionary<string, object> resource_home = fbServer.GetHomeFeed("more");
                if (resource_home == null || IsConnected == false)
                {
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                    new System.Action(delegate()
                    {
                        loadingcontrol_home.Visibility = Visibility.Collapsed;
                        LoadingIcon.Text = "Cannot load more feeds! :((";
                    }));
                    return;
                }
                ObservableCollection<HomeFeedViewModel> list = fbServer.ConvertToListFeeds(resource_home);
                if (list.Count == 0)
                {
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                    new Action(delegate()
                    {
                        loadingcontrol_home.Visibility = Visibility.Collapsed;
                        LoadingIcon.Text = "Cannot load more feeds! :((";
                    }));
                    return;
                }


                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                    new Action(delegate()
                    {
                        loadingcontrol_home.Visibility = Visibility.Collapsed;
                        rootdata.AddHomeFeeds(list);
                    }));
            }
            catch
            {
                return;
            }


        }

        /*
         * Bắt sự kiện thay đổi các Tab Control Home, Profile, Album, Picture, ...
         */
        private void tabControl1_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            try
            {
                CheckConnection();
                // TODO: Add event handler implementation here.
                if (tabFriends.IsSelected)
                {
                    // Chưa làm được thread chổ này
                    thread2 = new System.Threading.Thread(new System.Threading.ThreadStart(LoadFriendsInfo));
                    thread2.SetApartmentState(System.Threading.ApartmentState.STA);
                    //thread2.IsBackground = true;

                    System.Threading.Thread current = System.Threading.Thread.CurrentThread;
                    if (rootdata.FRIENDLIST.Count == 0)
                        thread2.Start();
                    //LoadFriendsInfo();
                }
                if (tabProfile.IsSelected)
                {
                    Stack_wall.Visibility = Visibility.Visible;
                    Info_control.Visibility = Visibility.Collapsed;
                    Stack_picture.Visibility = Visibility.Collapsed;
                    load_stt = "wall";
                    //List<object> temp = (List<object>)listbox_wall.ItemsSource;

                    if (rootdata.WALLFEEDLIST.Count == 0)
                    {
                        loadingcontrol_wall.Visibility = Visibility;
                        System.Threading.Thread load = new System.Threading.Thread(new System.Threading.ThreadStart(LoadWall));
                        load.Priority = System.Threading.ThreadPriority.Normal;
                        load.Start();
                    }
                }
                if (tabAlbum.IsSelected)
                {
                    load_stt = "album";
                    Get_loadSTT loadstt = new Get_loadSTT();
                    loadstt.Load_stt = "album";
                    loadingcontrol_album.Visibility = Visibility.Visible;
                    List<object> temp = (List<object>)listbox_album.ItemsSource;
                    if (temp.Count == 0)
                    {
                        System.Threading.Thread load = new System.Threading.Thread(new System.Threading.ThreadStart(Load_Album));
                        load.Priority = System.Threading.ThreadPriority.Normal;
                        load.Start();
                    }
                }
            }
            catch
            {
                return;
            }

        }

        /*
         * Load Friend của người dùng
         * Chưa làm đc multi thread chổ này
         */
        void LoadFriendsInfo()
        {
            try
            {
                IDictionary<string, object> resource_friends = fbServer.GetFriends();
                ObservableCollection<FriendViewModel> list = fbServer.ConvertToListFriends(resource_friends);

                this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate()
                    {
                        rootdata.AddFriendViewModel(list);
                        //listbox_friends.ItemsSource = list; // Break ở dòng này

                    }));
            }
            catch
            {
                return;
            }


        }


        /*
         * Bắt sự kiện thay đổi scroll phần Friend Tab
         * Chưa làm đc multi thread chổ này
         */
        private void scrollFriend_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            try
            {
                CheckConnection();
                if (e.ExtentHeight == (e.VerticalOffset + e.ViewportHeight) && ((LoadingIcon.Text == "Loading") || (IsConnected == true)))
                {
                    if (thread_load_friend_more != null) // Nếu tồn tại thread đang running thì sẽ ko create thread nào nữa
                        if (thread_load_friend_more.IsAlive)
                            return;
                    // Chưa làm được cái multi thread
                    //thread_load_friend_more = new System.Threading.Thread(new System.Threading.ThreadStart(LoadFriendMore));
                    //thread_load_friend_more.SetApartmentState(System.Threading.ApartmentState.STA);
                    //thread_load_friend_more.Start();
                    //thread_load_friend_more.Join();
                    LoadFriendMore();
                }
            }
            catch
            {
                return;

            }

        }

        /*
         * Load thêm Friend
         */
        private void LoadFriendMore()
        {
            try
            {
                CheckConnection();
                ObservableCollection<FriendViewModel> listmore = fbServer.GetMoreFriend();
                System.Threading.Thread owerThred = System.Threading.Thread.CurrentThread;

                if (listmore.Count == 0 || IsConnected == false)
                {
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                    new Action(delegate()
                    {
                        LoadingIcon_friends.Text = "Cannot load more friends! :((";
                    }));
                    return;
                }

                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                new Action(delegate()
                {

                    rootdata.AddFriendViewModel(listmore);

                }));
            }

            catch
            {
                return;
            }
        }

        private void ___No_Name__PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            // TODO: Add event handler implementation here.
            if (e.Key == Key.Enter)
            {
                ;
            }
        }

        /*
         * Bắt sự kiện Text Change khi tìm kiếm friend
         */
        private void ___No_Name__TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            try
            {
                ObservableCollection<FriendViewModel> result;
                string key = textboxsearch.Text;
                if (textboxsearch.Text == "")
                {
                    rootdata.ClearAllFriend();
                    rootdata.AddFriendViewModel(fbServer.ConvertToListFriends());

                    return;
                }
                if (thread_search_friend != null)
                    if (thread_search_friend.IsAlive)
                        thread_search_friend.Abort();

                thread_search_friend = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    result = fbServer.SearchFriend(key);
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(delegate()
                        {
                            rootdata.ClearAllFriend();
                            rootdata.AddFriendViewModel(result);
                        }));

                }));

                thread_search_friend.Start();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void button_notice_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            popup_notice.IsOpen = true;
        }

        private void button_friendrequest_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            popup_friendrequest.IsOpen = true;
        }

        /*
         *  PHẦN THẰNG THÀNH
         */

        private void Info_clicked(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                CheckConnection();
                if (Info_control.Visibility == Visibility.Collapsed || IsConnected == true)
                {
                    popup_menu.IsOpen = false;
                    Info_control.Visibility = Visibility.Visible;
                    Stack_picture.Visibility = Visibility.Collapsed;
                    Stack_wall.Visibility = Visibility.Collapsed;
                    LoadingIcon_info.Visibility = Visibility.Visible;
                    if (txt_bio.Visibility != Visibility.Visible)
                    {
                        System.Threading.ThreadStart start = delegate
                        {
                            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                               new System.Action(delegate()
                               {
                                   LoadInfo();
                                   LoadingIcon_info.Visibility = Visibility.Collapsed;
                               }));
                        };
                        System.Threading.Thread load = new System.Threading.Thread(start);
                        load.Priority = System.Threading.ThreadPriority.Normal;
                        load.Start();
                    }
                }
                else
                {
                    MessageBox.Show("No Connection");
                }
            }
            catch
            {
                return;
            }
            // TODO: Add event handler implementation here.




        }

        void LoadInfo()
        {
            try
            {
                IDictionary<string, object> data = (IDictionary<string, object>)fbServer.GetInfo((string)rootdata.personalInfo["id"]);
                if (data.ContainsKey("gender"))
                {
                    txt_gender.Text = (string)data["gender"];
                    txt_gender.Visibility = Visibility.Visible;
                    txb_gender.Visibility = Visibility.Visible;
                    img_gender.Visibility = Visibility.Visible;
                    gender.Visibility = Visibility.Visible;
                }
                if (data.ContainsKey("relationship_status"))
                {
                    txt_relationship.Text = (string)data["relationship_status"];
                    txt_relationship.Visibility = Visibility.Visible;
                    txb_relationship.Visibility = Visibility.Visible;
                    img_relationship.Visibility = Visibility.Visible; ;
                    relationship.Visibility = Visibility.Visible;
                }
                if (data.ContainsKey("quotes"))
                {
                    txt_quotes.Visibility = Visibility.Visible; ;
                    txt_quotes.Text = (string)data["quotes"];
                    txb_quotes.Visibility = Visibility.Visible;
                    quotes.Visibility = Visibility.Visible;
                    img_quotes.Visibility = Visibility.Visible;
                }
                if (data.ContainsKey("bio"))
                {
                    txt_bio.Text = (string)data["bio"];
                    txb_bio.Visibility = Visibility.Visible;
                    txt_bio.Visibility = Visibility.Visible;
                    bio.Visibility = Visibility.Visible;
                    img_bio.Visibility = Visibility.Visible;
                }
                if (data.ContainsKey("birthday"))
                {
                    txt_birthday.Text = (string)data["birthday"];
                    txt_birthday.Visibility = Visibility.Visible;
                    birthday.Visibility = Visibility.Visible;
                    txb_birthday.Visibility = Visibility.Visible;
                    img_birthday.Visibility = Visibility.Visible;

                }
                if (data.ContainsKey("religion"))
                {
                    txt_religion.Visibility = Visibility.Visible; ;
                    txt_religion.Text = (string)data["religion"];
                    txb_religion.Visibility = Visibility.Visible;
                    religion.Visibility = Visibility.Visible;
                    img_religion.Visibility = Visibility.Visible;
                }
                if (data.ContainsKey("languages"))
                {
                    string _language = "";
                    List<object> temp = (List<object>)data["languages"];
                    for (int i = 0; i < temp.Count; i++)
                    {
                        IDictionary<string, object> temp2 = (IDictionary<string, object>)temp[i];
                        string temp4 = (string)temp2["name"];
                        _language += "\n + " + temp4;
                    }
                    txt_language.Text = _language.Substring(1);
                    txt_language.Visibility = Visibility.Visible;
                    txb_language.Visibility = Visibility.Visible;
                    img_language.Visibility = Visibility.Visible;
                    language.Visibility = Visibility.Visible;

                }
                if (data.ContainsKey("email"))
                {
                    txt_email.Visibility = Visibility.Visible; ;
                    txt_email.Text = (string)data["email"];
                    txb_email.Visibility = Visibility.Visible;
                    email.Visibility = Visibility.Visible;
                    img_email.Visibility = Visibility.Visible;
                }
                if (data.ContainsKey("education"))
                {
                    string _edu = "";
                    List<object> temp = (List<object>)data["education"];
                    for (int i = 0; i < temp.Count; i++)
                    {
                        IDictionary<string, object> temp2 = (IDictionary<string, object>)temp[i];
                        IDictionary<string, object> temp3 = (IDictionary<string, object>)temp2["school"];
                        string temp_education = (string)temp3["name"];
                        _edu += "\n +" + temp_education;
                        string ggg = _edu;
                    }
                    txt_education.Text = _edu.Substring(1);
                    txb_education.Visibility = Visibility.Visible;
                    img_education.Visibility = Visibility.Visible;
                    education.Visibility = Visibility.Visible;
                    txt_education.Visibility = Visibility.Visible;
                }
                if (data.ContainsKey("work"))
                {
                    string _work = "";
                    List<object> temp = (List<object>)data["work"];
                    for (int i = 0; i < temp.Count; i++)
                    {
                        IDictionary<string, object> temp2 = (IDictionary<string, object>)temp[i];
                        IDictionary<string, object> temp3 = (IDictionary<string, object>)temp2["employer"];
                        string temp_work = (string)temp3["name"];
                        _work += "\n +" + temp_work;
                    }
                    txt_work.Text = _work.Substring(1);
                    txt_work.Visibility = Visibility.Visible;
                    txb_work.Visibility = Visibility.Visible;
                    img_work.Visibility = Visibility.Visible;
                    work.Visibility = Visibility.Visible;
                }

            }
            catch
            {
                return;
            }

        }

        private void DoChanged_Profile_Wall(object sender, ScrollChangedEventArgs e)
        {
            try
            {
                CheckConnection();
                if (e.ExtentHeight == (e.VerticalOffset + e.ViewportHeight) && (LoadingIcon_wall.Text == "Loading") || (IsConnected == true))
                {
                    if (thread != null) // Nếu tồn tại thread đang running thì sẽ ko create thread nào nữa
                        if (thread.IsAlive)
                            return;
                    loadingcontrol_wall.Visibility = Visibility.Visible;
                    thread = new System.Threading.Thread(new System.Threading.ThreadStart(LoadWallMore));
                    thread.Start();
                }
            }
            catch
            {
                return;
            }

        }

        private void DoChanged_Profile_Picture(object sender, ScrollChangedEventArgs e)
        {
            try
            {
                CheckConnection();
                if (load_stt == "picture")
                {
                    if (e.ExtentHeight == (e.VerticalOffset + e.ViewportHeight) && (LoadingIcon_picture.Text == "Loading") || (IsConnected == true))
                    {
                        if (thread != null) // Nếu tồn tại thread đang running thì sẽ ko create thread nào nữa
                            if (thread.IsAlive)
                                return;
                        loadingcontrol_picture.Visibility = Visibility.Visible;
                        thread = new System.Threading.Thread(new System.Threading.ThreadStart(LoadPictureMore));
                        thread.Start();
                    }
                }
            }
            catch
            {
                return;
            }

        }

        private void Menu_Wall_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                // TODO: Add event handler implementation here.
                load_stt = "wall";
                popup_menu.IsOpen = false;
                LoadingIcon_wall.Visibility = Visibility.Visible;
                Stack_wall.Visibility = Visibility.Visible;
                Info_control.Visibility = Visibility.Collapsed;
                //Stack_picture.Visibility = Visibility.Collapsed;
                thread2 = new System.Threading.Thread(new System.Threading.ThreadStart(LoadWall));
                thread2.Start();
            }
            catch
            {
                MessageBox.Show("No Connection");
            }

        }

        void LoadWall()
        {
            try
            {
                IDictionary<string, object> resource_wall = fbServer.GetWall();
                ObservableCollection<HomeFeedViewModel> list = fbServer.ConvertToListWall(resource_wall);

                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                   new Action(delegate()
                   {

                       rootdata.AddWall(list);
                       loadingcontrol_wall.Visibility = Visibility.Collapsed;

                   }));
            }
            catch
            {
                return;
            }

        }

        private void LoadWallMore()
        {
            try
            {
                CheckConnection();
                IDictionary<string, object> resource_wall = fbServer.GetWallMore("more");
                if (resource_wall == null || IsConnected == false)
                {
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                    new System.Action(delegate()
                    {
                        LoadingIcon_wall.Text = "Cannot load more feeds! :((";
                        loadingcontrol_wall.Visibility = Visibility.Collapsed;
                    }));

                    return;
                }
                ObservableCollection<HomeFeedViewModel> list = fbServer.ConvertToListWall(resource_wall);
                if (list.Count == 0)
                {
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                    new Action(delegate()
                    {
                        LoadingIcon_wall.Text = "Cannot load more feeds! :((";
                        loadingcontrol_wall.Visibility = Visibility.Collapsed;
                    }));
                    return;
                }

                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                new Action(delegate()
                {
                    //System.Threading.Thread.Sleep(2000);
                    //rootdata.WALLFEEDLIST = list_source;
                    rootdata.AddWall(list);
                    loadingcontrol_wall.Visibility = Visibility.Collapsed;
                    //listbox_wall.Items.Refresh();
                }));

            }
            catch
            {
                return;
            }

        }

        private void Menu_Picture_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                load_stt = "picture";
                popup_menu.IsOpen = false;
                loadingcontrol_picture.Visibility = Visibility.Visible;
                LoadingIcon_picture.Visibility = Visibility.Visible;
                Stack_picture.Visibility = Visibility.Visible;
                Stack_wall.Visibility = Visibility.Collapsed;
                Info_control.Visibility = Visibility.Collapsed;
                List<object> temp = (List<object>)listbox_picture.ItemsSource;
                if (temp.Count == 0)
                {
                    thread2 = new System.Threading.Thread(new System.Threading.ThreadStart(LoadPicture));
                    thread2.Start();
                }
            }
            catch
            {
                return;
            }

        }

        void LoadPicture()
        {
            try
            {
                IDictionary<string, object> resource_picture = fbServer.GetPicture();
                List<object> list = fbServer.ConvertToListPicture(resource_picture);
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                   new Action(delegate()
                   {
                       loadingcontrol_picture.Visibility = Visibility.Collapsed;
                       rootdata.PROFILEPICTURE = list;
                   }));
            }
            catch
            {
                return;
            }

        }

        private void Profile_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            try
            {
                CheckConnection();
                if (!IsConnected)
                {
                    return;
                }
                List<object> myprofile = new List<object>();
                if (load_stt == "wall")
                    myprofile = (List<object>)listbox_wall.Items.SourceCollection;
                if (load_stt == "picture")
                    myprofile = (List<object>)listbox_picture.Items.SourceCollection;
                for (int i = 0; i < myprofile.Count; i++)
                {
                    if (((CType)myprofile[i]).isChecked == true)
                    {
                        if (e.OriginalSource.GetType() == typeof(RadioButton))
                        {
                            if (profile_detail != null)
                            {
                                profile_detail.Close();
                            }
                            profile_detail = new WindowsDetail(load_stt, ((CType)myprofile[i]).id, myprofile, (string)rootdata.personalInfo["id"], (string)rootdata.personalInfo["name"], 100, 330, AccessToken);
                            profile_detail.Show();
                        }
                        else if (e.OriginalSource.GetType() == typeof(Button))
                        {
                            MessageBox.Show("Wrong");
                        }
                    }
                }
            }
            catch
            {
                return;
            }

        }

        private void LoadPictureMore()
        {
            try
            {
                CheckConnection();
                IDictionary<string, object> resource_picture = fbServer.GetPictureMore("more");
                if (resource_picture == null || IsConnected == false)
                {
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                    new System.Action(delegate()
                    {
                        LoadingIcon_picture.Text = "Cannot load more pictures! :((";
                        loadingcontrol_picture.Visibility = Visibility.Hidden;
                    }));

                    return;
                }
                List<object> list = fbServer.ConvertToListPicture(resource_picture);
                if (list.Count == 0)
                {
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                    new Action(delegate()
                    {
                        LoadingIcon_picture.Text = "Cannot load more pictures! :((";
                        loadingcontrol_picture.Visibility = Visibility.Hidden;
                    }));
                    return;
                }
                List<object> list_source = (List<object>)rootdata.PROFILEPICTURE;

                for (int i = 0; i < list.Count; i++)
                    list_source.Add(list[i]);
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                new Action(delegate()
                {
                    //System.Threading.Thread.Sleep(2000);
                    loadingcontrol_picture.Visibility = Visibility.Hidden;
                    rootdata.PROFILEPICTURE = list_source;
                    listbox_picture.Items.Refresh();
                }));

            }
            catch
            {
                return;
            }
        }

        /*
         * Phần ALBUM
         */
        private void Album_item_clicked(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckConnection();
                if (!IsConnected)
                {
                    return;
                }
                List<object> myalbum = (List<object>)listbox_album.Items.SourceCollection;
                for (int i = 0; i < myalbum.Count; i++)
                {
                    if (((CType)myalbum[i]).isChecked == true)
                    {

                        if (e.OriginalSource.GetType() == typeof(RadioButton))
                        {
                            if (album_detail != null)
                            {
                                album_detail.Close();
                            }
                            album_detail = new WindowsDetail("album", ((CType)myalbum[i]).id, null, (string)rootdata.personalInfo["id"], (string)rootdata.personalInfo["name"], 100, 330, AccessToken);
                            album_detail.Show();
                        }
                        else if (e.OriginalSource.GetType() == typeof(Button))
                        {
                            MessageBox.Show("Wrong");
                        }
                    }
                }
            }
            catch
            {
                return;
            }

        }

        private void DoChanged_loadmore_album(object sender, ScrollChangedEventArgs e)
        {
            try
            {
                CheckConnection();
                if (e.ExtentHeight == (e.VerticalOffset + e.ViewportHeight) && (LoadingIcon_album.Text == "Loading") || (IsConnected == true))
                {
                    if (thread != null) // Nếu tồn tại thread đang running thì sẽ ko create thread nào nữa
                        if (thread.IsAlive)
                            return;
                    thread = new System.Threading.Thread(new System.Threading.ThreadStart(Load_Album_More));
                    thread.Start();
                }
            }
            catch
            {
                return;
            }

        }

        void Load_Album_More()
        {
            try
            {
                CheckConnection();
                IDictionary<string, object> resource_album = fbServer.GetAlbums_more("more");
                if (resource_album == null || IsConnected == false)
                {
                    LoadingIcon_album.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate()
                    {
                        LoadingIcon_album.Text = "Can't load more albums!";
                        loadingcontrol_album.Visibility = Visibility.Collapsed;
                    }));
                    return;
                };
                List<object> list = fbServer.ConverttoListAlbums(resource_album);
                if (list.Count == 0)
                {
                    LoadingIcon_album.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate()
                    {
                        LoadingIcon_album.Text = "Can't load more albums!";
                        loadingcontrol_album.Visibility = Visibility.Collapsed;
                    }
                    ));
                    return;
                }
                List<object> list_source = rootdata.PROFILEALBUM;
                for (int i = 0; i < list.Count; i++)
                    list_source.Add(list[i]);
                listbox_album.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {
                    //System.Threading.Thread.Sleep(2000);
                    //listbox_album.ItemsSource = list_source;
                    loadingcontrol_album.Visibility = Visibility.Collapsed;
                    rootdata.PROFILEALBUM = list_source;
                    listbox_album.Items.Refresh();
                }));
            }
            catch
            {
                return;
            }

        }

        void Load_Album()
        {
            try
            {
                IDictionary<string, object> resource_album = fbServer.GetAlbums();
                List<object> temp = fbServer.ConverttoListAlbums(resource_album);
                listbox_album.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                {
                    //listbox_album.ItemsSource = fbServer.ConverttoListAlbums(resource_album);
                    loadingcontrol_album.Visibility = Visibility.Collapsed;
                    rootdata.PROFILEALBUM = temp;
                }));
            }
            catch
            {
                return;
            }

        }

        void PrepairAutoUpdate()
        {
            try
            {
                autoupdate.DoAddHomeFeedFirst = (ObservableCollection<HomeFeedViewModel> list) =>
               {
                   this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                       {
                           if (rootdata.HOMEFEEDLIST.Count < 75)
                               rootdata.AdHomeFeedsFirt(list);
                           else
                           {
                               rootdata.ClearAllHomeFeed();
                               LoadHomeFeed();
                           }
                       }));
               };

                autoupdate.DoAddNotificationFirst = (ObservableCollection<NotificationViewModel> list) =>
                    {
                        this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                        {
                            rootdata.AddNotify(list);
                        }));
                    };

                autoupdate.DoAddFriendRequest = (ObservableCollection<FriendRequestViewModel> list) =>
                    {
                        this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                        {
                            rootdata.AddFriendRequest(list);
                        }));
                    };

                autoupdate.DoAddAnnouncement = (string message) =>
                    {
                        this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                        {
                            announcementSys.AddAnnounment(message);
                        }));
                    };


                autoupdate.DoAddWall = () =>
                    {
                        this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                        {
                            rootdata.ClearAllWall();
                            LoadWall();
                        }));
                    };

                autoupdate.DoAddAnnouncement = (string message) =>
                    {
                        this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                        {
                            announcementSys.AddAnnounment(message);
                        }));
                    };
            }
            catch
            {
                return;
            }
        }
    }
}